import axios from 'axios';
import router from '../router/index'
import { getVersionsUrl } from '../common-func/common-func'
let http = axios.create({
//	baseURL: 'http://47.98.119.130/yaminew/public/',
	baseURL:'api/',
	withCredentials: true,
	respomseType:"json",
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
	},
	transformRequest: [function(data) {
		let newData = '';
		for(let k in data) {
			if(data.hasOwnProperty(k) === true) {
				newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&';
			}
		}
		return newData;
	}]
});

function apiAxios(method, arg) {
	var url = '', params , response; 
	if(arg.length === 1 && typeof arg[0] != "string") {
		params = arg[0]
	} else {
		url = arg[0];
		if(typeof arg[1] === 'object') {
			params = arg[1]
			response = arg[2]
		} else {
			response = arg[1]
		}
	}
	// 根据当前版本，修改路径
	url = getVersionsUrl(url)
	http({
		method: method,
		url: url,
		data: method === 'POST' || method === 'PUT' ? params : null,
		params: method === 'GET' || method === 'DELETE' ? params : null,
	}).then(function(res) {
		if(res.status != 200) {
			router.push("/serverError")
			return
		}
		response(res.data);
	}).catch(function(err) {
		response(err);
	})
}

export default {
	get: function() {
		return apiAxios('GET', arguments)
	},
	post: function() {
		return apiAxios('POST', arguments)
	},
	put: function() {
		return apiAxios('PUT', arguments)
	},
	delete: function() {
		return apiAxios('DELETE', arguments)
	}
}